package org.example.dao;

import org.example.DBConnection;
import org.example.entity.Order;
import org.example.entity.OrderItem;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaomengzi
 * @create 2025-08-04 下午2:52
 */
public class OrderDAO {
    Connection connection;
    OrderItemDAO orderItemDAO;
    public OrderDAO() throws SQLException {
        try {
            connection = DBConnection.getConnection();
            orderItemDAO = new OrderItemDAO();
        } catch (SQLException e) {
            throw new SQLException("数据库连接失败", e);
        }
    }
    //创建新订单
    public int createOrder(Order order) throws SQLException {
        String sql = "insert into orders (user_id,total_amount,status,shipping_address,create_date,update_date) values (?,?,?,?,?,?,?)";
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, order.getUserId());
            ps.setBigDecimal(2,order.getTotalAmount());
            ps.setString(3,order.getStatus());
            ps.setString(4,order.getShippingAddress());
            ps.setTimestamp(5, Timestamp.valueOf(order.getCreateDate()));
            ps.setTimestamp(6, Timestamp.valueOf(order.getUpdateDate()));

            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    int id = rs.getInt(1);
                    if(order.getOrderItems() != null){
                        for (OrderItem item: order.getOrderItems()) {
                            item.setOrderId(id);
                            int orderItemId = orderItemDAO.createOrderItem(item);
                            if(orderItemId <= 0){
                                return -1;
                            }
                        }
                    }
                    return id;
                }
            }
        }
        return -1;
    }
    //通过id获取订单
    public Order getOrder(int orderId) throws SQLException {
        String sql = "select * from orders where order_id=?";
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, orderId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    Order order = new Order();
                    order.setId(rs.getInt("order_id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setTotalAmount(rs.getBigDecimal("total_amount"));
                    order.setStatus(rs.getString("status"));
                    order.setShippingAddress(rs.getString("shipping_address"));
                    order.setCreateDate(rs.getTimestamp("created_at").toLocalDateTime());
                    order.setUpdateDate(rs.getTimestamp("updated_at").toLocalDateTime());
                    order.setOrderItems((ArrayList<OrderItem>) orderItemDAO.getOrderItems(orderId));
                    return order;
                }
            }
        }
        return null;
    }
    //通过用户id获取所有订单
    public ArrayList<Order> getOrdersByUserId(int userId) throws SQLException {
        String sql = "select * from orders where user_id=?";
        List<Order> orders = new java.util.ArrayList<>();
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Order order = new Order();
                    order.setId(rs.getInt("order_id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setTotalAmount(rs.getBigDecimal("total_amount"));
                    order.setStatus(rs.getString("status"));
                    order.setShippingAddress(rs.getString("shipping_address"));
                    order.setCreateDate(rs.getTimestamp("created_at").toLocalDateTime());
                    order.setUpdateDate(rs.getTimestamp("updated_at").toLocalDateTime());
                    order.setOrderItems(orderItemDAO.getOrderItems(order.getId()));
                    orders.add(order);
                }
            }
        }
        return (ArrayList<Order>) orders;
    }
    //更新订单状态
    public boolean updateOrder(int orderid,String status) throws SQLException {
        List<String> statusList = java.util.Arrays.asList("pending","paid","shipped","delivered","cancelled");
        if(!statusList.contains(status)){
            return false;
        }
        String sql = "update orders set status=?,update_date=? where order_id=?";
        try (PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, status);
            ps.setTimestamp(2, Timestamp.valueOf(LocalDateTime.now()));
            ps.setInt(3, orderid);
            int rows = ps.executeUpdate();
            return rows > 0;
        }
    }

}
